package com.asj.house.service.impl;

import com.asj.house.entity.HouseVisit;
import com.asj.house.mapper.HouseVisitMapper;
import com.asj.house.service.HouseVisitService;
import com.asj.house.utils.TimeUtilCustomize;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 访问量表 服务实现类
 * </p>
 *
 * @author asj
 * @since 2021-03-05
 */
@Service
public class HouseVisitServiceImpl extends ServiceImpl<HouseVisitMapper, HouseVisit> implements HouseVisitService {

    @Override
    public void visitAccess() {
        //当前时间 格式：yyyy-MM-dd HH:00:00
        String dateH = TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_TIME_FORMAT_H, new Date());
        //当前时间 格式：yyyy-MM-dd
        String dateD = TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_DAY_FORMAT, new Date());

        //判断当前时间记录 数据库中是否存在
        HouseVisit visit = checkExits(dateH);

        if (Objects.isNull(visit)) {
            //添加
            insertVisit(dateH, dateD);
        }else {
            //更新
            updateVisit(dateH);
        }

    }

    private void updateVisit(String dateH) {
        QueryWrapper<HouseVisit> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HouseVisit::getDt, dateH)
                .eq(HouseVisit::getDeleted, 0);
        HouseVisit visit = baseMapper.selectOne(queryWrapper);

        Integer oldVisit = visit.getVisit();
        int newVisit = oldVisit + 1;
        visit.setVisit(newVisit);

        baseMapper.updateById(visit);
    }

    private void insertVisit(String dateH, String dateD) {
        HouseVisit houseVisit = HouseVisit.builder()
                .dt(dateH)
                .dtD(dateD)
                .visit(1)
                .build();

        baseMapper.insert(houseVisit);
    }

    private HouseVisit checkExits(String dateH) {
        QueryWrapper<HouseVisit> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HouseVisit::getDt, dateH)
                .eq(HouseVisit::getDeleted, 0);

        return baseMapper.selectOne(queryWrapper);
    }
}
